<template>
  <div class="content-section">
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <span>我的下载</span>
        </div>
      </template>

      <!-- 列表加载状态 -->
      <div class="report-list" v-loading="loading">
        <div
          v-for="(item, index) in reportList"
          :key="index"
          class="report-card"
        >
          <div class="report-info">
            <div class="cover-image">
              <img :src="item.coverPic" alt="报告封面" />
              <div class="img-title">{{ item.title }}</div>
            </div>

            <div class="report-details">
              <div class="title-section">
                  <el-icon><Tickets /></el-icon>
                  <el-tooltip
                    :content="item.title"
                    placement="top"
                    effect="dark"
                  >
                    <span
                   @click="toDetail(item)"
                      class="report-title-link"
                    >
                      {{ item.title }}
                    </span>
                  </el-tooltip>
                
                </div>
              <div class="meta-info">
                <div class="meta-item">
                  <el-icon><EditPen /></el-icon>
                  <span>{{ item.author }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Timer /></el-icon>
                  <span>{{
                    dayjs.unix(Number(item.publishTime)).format("YYYY-MM-DD")
                  }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Tickets /></el-icon>
                  <span>{{ item.sizeNum }}</span>
                </div>
                <el-tag :type="item.price === '免费' ? 'primary' : 'warning'">
                  {{ item.price === "免费" ? "免费" : `¥${item.price}` }}
                </el-tag>
              </div>
              <div class="upload-time">
                <span class="label">{{ uploadTimeLabel }}</span>
                <span>{{
                  dayjs.unix(Number(item.publishTime)).format("YYYY-MM-DD")
                }}</span>
              </div>
            </div>
          </div>

          <div class="action-panel">
            <!-- 下载按钮，带 loading -->
            <el-button
              :icon="Download"
              link
              :loading="downLoading === item.code"
              class="action-btn"
              @click="DWReport(item)"
            >
              {{ editText }}
            </el-button>
            <!-- 分享按钮 -->
            <el-button
              :icon="Share"
              link
              class="action-btn"
              @click="SRReport(item)"
            >
              {{ deleteText }}
            </el-button>
          </div>
        </div>
        <el-empty
    v-if="!loading && reportList.length === 0"
    style="margin: 80px auto;"
    description="当前暂无下载数据"
    :image-size="120"
  />
      </div>

      <!-- 分页 -->
      <Pagination
        :total="Number(props.total)"
        :page="currentPage"
        :limit="pageSize"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </el-card>
  </div>
</template>

<script setup>
import { download } from '../../api/Download'
import { Download, Share, EditPen, Timer, Tickets } from '@element-plus/icons-vue'
import { ref, computed, onMounted,watch } from 'vue'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
const router = useRouter()
const props = defineProps({
  downloadsdata: {
    type: Array,
    default: () => [],
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  total: { type: Number, default: 0 },
  initialPage: { type: Number, default: 1 },
  initialSize: { type: Number, default: 10 },
})
const emit = defineEmits(['refresh'])

// 文本变量
const uploadTimeLabel = ref('上传时间：')
const editText = ref('下载')
const deleteText = ref('分享')

// 列表数据 & 状态
const reportList = ref(props.downloadsdata)
// 添加数据监听
watch(() => props.downloadsdata, (newVal) => {
  reportList.value = newVal
})

const downLoading = ref('')

// 分页
const currentPage = ref(props.initialPage)
const pageSize = ref(props.initialSize)
watch(() => props.initialPage, v => currentPage.value = v)
watch(() => props.initialSize, v => pageSize.value = v)


watch(() => props.uploadsdata, v => reportList.value = v)


const handleCurrentChange = (page) => {
  currentPage.value = page
  emit('refresh', { pageNum: page, pageSize: pageSize.value })
}
const handleSizeChange = (limit) => {
  pageSize.value = limit
  currentPage.value = 1
  emit('refresh', { pageNum: 1, pageSize: limit })
}


// // 加载下载列表
//  const loadReports = async() => {
//   loading.value = true
//   try {
//     const res = await download.myReporDowntList()
//     reportList.value = res.data.myDownList.info || []
//   } catch {
//     ElMessage.error('加载失败')
//   } finally {
//     loading.value = false
//   }
// }

// 下载报告
 const DWReport =async item => {
  downLoading.value = item.code
  try {
    const res = await download.downloadReport({ code: item.code })
    if (res.code === 0) {
      // 创建 a 标签触发下载
      const a = document.createElement('a')
      a.href = res.data.userDown.pdfDir
      a.download = ''
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      ElMessage.success('下载开始')
    } else {
      ElMessage.error(res.msg || '下载失败')
    }
  } catch {
    ElMessage.error('下载出错')
  } finally {
    downLoading.value = ''
  }
}

// 分享报告
 const SRReport=async(item)=> {
  try {
    const res = await download.shareReport({ code: item.code })
    const url = window.location.href
    await navigator.clipboard.writeText(url)
    ElMessage.success('链接已复制到剪贴板')
  } catch {
    ElMessage.error('复制失败')
  }
}


const toDetail=(item)=>{
  if (item.price === '0') {
    // 解析免费报告详情页的完整URL
    const freeUrl = router.resolve({
      name: 'productDetail',
      params: { code: item.code }
    }).href;

    // 在新标签页打开免费报告
    window.open(freeUrl, '_blank');
  } else {
    // 解析付费报告详情页的完整URL
    const paidUrl = router.resolve({
      name: 'productDetailcharge',
      params: { code: item.code }
    }).href;

    // 在新标签页打开付费报告
    window.open(paidUrl, '_blank');
  }
}

onMounted(()=>{})
</script>

<style lang="scss" scoped>
.content-section {
  animation: fadeIn 0.3s ease;
}
.upload-card {
  height: 730px;
  margin: 0;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
}
.report-list {
  height: 578px;
  overflow-y: auto;
  &::-webkit-scrollbar {
      width: 6px;
    }
    &::-webkit-scrollbar-thumb {
      background: rgba(0, 0, 0, 0.2);
      border-radius: 4px;
    }
}
.report-card {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  transition: background-color 0.2s;
  &:hover {
    background-color: rgba(0, 128, 209, 0.05);
  }
  &:last-child {
    border-bottom: none;
  }
}
.report-info {
  display: flex;
  gap: 20px;
  flex: 1;
  min-width: 0;
}
.cover-image {
  width: 120px;
  height: 175px;
  position: relative;
  .img-title {
    position: absolute;
    top: 25%;
    left: 45%;
    /* 先把文字中心移到容器中心 */
    transform: translate(-50%, -50%) rotate(-5deg);
    /* 文字样式 */
    font-size: 7px;
    font-weight: bold;
    font-style: italic;
    color: #ffffff;
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
    white-space: nowrap;
    pointer-events: none;
    text-align: center;
      width: 100px;
      white-space: nowrap; /* 防止文本换行 */
      overflow: hidden; /* 隐藏溢出的内容 */
      text-overflow: ellipsis; /* 显示省略号来代表被修剪的文本 */
  }
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
.report-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  gap: 8px;
  .title-section {
    display: flex;
    align-items: center;
    gap: 8px;
    .report-title {
      font-size: 16px;
      font-weight: 600;
      color: #151618;
      margin: 0;
    }
    .el-tag {
      font-size: 14px;
      padding: 4px 10px;
    }
  }
  .meta-info {
    display: flex;
    align-items: center;
    gap: 20px;
    color: rgba(21, 22, 24, 0.72);
    .meta-item {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 13px;
      .el-icon {
        font-size: 14px;
        color: rgba(21, 22, 24, 0.56);
      }
    }
  }
  .upload-time {
    font-size: 13px;
    color: rgba(21, 22, 24, 0.72);
  }
}
.action-panel {
  width: 20%;
  display: flex;
  justify-content: space-around;
  align-items: center;
  .action-btn {
    color: #0080d1;
    font-size: 14px;
    padding: 0;
  }
}
.icon-icon_pdf {
  color: #ff7861;
  font-size: 22px;
}
.report-title-link {
  display: inline-block;
  max-width: 320px; /* 根据你的布局调整宽度 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #409eff; /* 链接颜色，可按需调整 */
  cursor: pointer;
  text-decoration: none;
}
.report-title-link:hover {
  text-decoration: underline;
}
</style>
